package com.gdth.bank.ui;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.gdth.bank.BankApplication;
import com.gdth.bank.R;
import com.gdth.bank.activity.CjkhPhotoActivity;
import com.gdth.bank.activity.CjkhjlActivity;
import com.gdth.bank.adapter.CjkhFjxxListViewAdapter;
import com.gdth.bank.event.CjkhjlListEvent;
import com.gdth.bank.presenter.CjkhFjxxPresenter;
import com.gdth.bank.utils.AppUtil;
import com.gdth.bank.view.CjkhFjxxView;
import com.gdth.bank.widget.BankDrawDownListTextView;
import com.gdth.bank.widget.image.Bimp;
import com.gdth.core.annotation.view.ViewInject;
import com.gdth.core.widget.BaseFrameLayout;
import com.gdth.database.bean.TAppFjxxb;
import com.gdth.database.bean.TAppYh;
import com.gdth.model.Item;
import com.gdth.utils.ToolUtil;
import com.gdth.utils.UUIDUtil;
import com.gdth.widget.dialog.BaseToast;

import org.greenrobot.eventbus.EventBus;

/**
 * 采集客户其他信息页面
 * @author arvin
 *
 */
public class CjkhQtxxFragment extends BaseFrameLayout implements CjkhFjxxView{
	
	@ViewInject(id=R.id.cjkh_qtxx_fjzl) BankDrawDownListTextView drawDownList_fjzl;
	@ViewInject(id=R.id.cjkh_qtxx_fjmc)
	EditText edit_fjmc;
	@ViewInject(id=R.id.cjkh_qtxx_tp) ImageView img_tp;
	
	@ViewInject(id=R.id.qtxx_gridview, itemClick="onItemClick") ListView listView_fjxx;

	@ViewInject(id=R.id.bfjl_save)
	Button bfjl_save;
	private CjkhjlActivity activity;
	
	TAppFjxxb mTAppFjxxb;
	
	String savePath, jcuuid, uuid, wjlx = "jpg";
	String savePath1, uuid1;
	
	List<Item> fjlxList = new ArrayList<Item>();
	
	private CjkhFjxxListViewAdapter adapter;
	
	private List<TAppFjxxb> fjxxList;
	
	private TAppYh mTAppYh;
	
	CjkhFjxxPresenter presenter;
	
	public CjkhQtxxFragment(Context context){
		super(context, R.layout.fragment_cjkhjl_qtxx);
		
		this.activity = (CjkhjlActivity) context;
	}
	
	public void initializeView(){
		fjlxList = AppUtil.getCanshuByType(this.context, AppUtil.SHARE_DATA_FJLX);
		drawDownList_fjzl.setLabel("附件种类：");
		drawDownList_fjzl.setItem(fjlxList);
		drawDownList_fjzl.setValue("1");
		
//		edit_fjmc.setLabel("附件名称：");
//		edit_fjmc.setHint("请填写附件名称，20个字以内");
//		edit_fjmc.addTextChangedListener(40);
//		edit_fjmc.setImage(null);
		
		fjxxList = new ArrayList<TAppFjxxb>();
		adapter = new CjkhFjxxListViewAdapter(this.context, fjxxList);
		adapter.setFjlx(fjlxList);
		listView_fjxx.setAdapter(adapter);
		
		Bimp.getInstance().reset();
		
		mTAppYh = BankApplication.mInstance.getCurrentUser();
		bfjl_save.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				save();
			}
		});
		img_tp.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				selectImage();
			}
		});
	}
	
	public void initializePresenter(){
		presenter = new CjkhFjxxPresenter(this);
	}

	/**
	 * 设置jcuuid，并查询所有附件
	 * @param jcuuid
	 */
	public void setJcuuid(String jcuuid){
		this.jcuuid = jcuuid;
		presenter.getFjxxByUuid(jcuuid);
	}
	
	/**
	 * 点击拍照
	 * @param arg0
	 */
	public void selectImage() {
		String status=Environment.getExternalStorageState(); 
		if(status.equals(Environment.MEDIA_MOUNTED)) {
//			Intent mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//			mIntent.putExtra(MediaStore.EXTRA_OUTPUT, getUri());
//			mIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
//			activity.startActivityForResult(mIntent, AppUtil.activity_photo_requestcode);
			Intent mIntent = new Intent();
			mIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
			mIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
			mIntent.putExtra(MediaStore.EXTRA_OUTPUT, getUri());//将拍取的照片保存到指定URI
			mIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
			activity.startActivityForResult(mIntent, AppUtil.activity_photo_requestcode);
		}  else { 
			BaseToast.getInstance().ShowSystemToast(context, "没有储存卡"); 
		} 
	}
	
	/**
	 * 保存图片路径
	 * @return
	 */
	private Uri getUri(){
		uuid1 = UUIDUtil.getUUID();
		String name = uuid1 + "." + wjlx;
		savePath1 = ToolUtil.getFilePath(name);
		String path = ToolUtil.getFileFullPath(savePath1);
		File file = new File(path);
		Uri imageUri = null;
		if (Build.VERSION.SDK_INT >= 24) {
			imageUri =  FileProvider.getUriForFile(activity, "com.jph.takephoto.fileprovider", file);//通过FileProvider创建一个content类型的Uri
		} else {
			imageUri = Uri.fromFile(file);
		}
//		Uri imageUri = Uri.fromFile(file);
		
		return imageUri;
	}
	
	
	/**
	 * 图片选择gridview点击事件
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 */
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
		Intent intent = new Intent(this.context, CjkhPhotoActivity.class);
		intent.putExtra("ID", arg2);
		intent.putExtra("jcuuid", jcuuid);
		this.context.startActivity(intent);
	}
	
	/**
	 * 拍照后保存附件信息
	 */
	public void saveImage(){
		try {
			uuid = uuid1;
			savePath = savePath1;
			//img_tp.setImageBitmap(Bimp.revitionImageSize(ToolUtil.getFileFullPath(savePath)));
			Bimp.setCompressor(ToolUtil.getFileFullPath(savePath),img_tp);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private long lastTime = 0;
	public void save() {
		if(System.currentTimeMillis() - lastTime  < 1000) {
			return ;
		}
		lastTime = System.currentTimeMillis();
		EventBus.getDefault().post(new CjkhjlListEvent(CjkhjlListEvent.refreshList));

		Object obj = drawDownList_fjzl.getkey();
		int fjlx = 0;
		if (obj != null) {
			fjlx = Integer.valueOf(obj.toString());
		} else {
			showMessage("附件类型不能为空");
			return;
		}
		String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		String fjmc = edit_fjmc.getText().toString();
		Pattern p = Pattern.compile(regEx);
		Matcher m =p.matcher(fjmc);
		if (fjmc.equals("")) {
			showMessage("附件名称不能为空");
			return;
		}
		if(m.find()){
			showMessage("附件名称不允许输入特殊符号");
			return;
		}
		
		if (savePath == null || savePath.equals("")) {
			showMessage("请先拍照");
			return;
		}
		mTAppFjxxb = new TAppFjxxb();
		mTAppFjxxb.setAppdz(savePath);
		mTAppFjxxb.setCjsj(new Date());
		mTAppFjxxb.setGnmk(1);
		mTAppFjxxb.setSczt(0);
		mTAppFjxxb.setSfz(mTAppYh.getZh());
		mTAppFjxxb.setUuid(uuid);
		mTAppFjxxb.setWjlx(wjlx);
		mTAppFjxxb.setFjlx(fjlx);
		
		mTAppFjxxb.setWjmc(edit_fjmc.getText().toString() + "." + wjlx);
		mTAppFjxxb.setWybs(jcuuid);
		mTAppFjxxb.setZdlx(1);
		
		presenter.save(mTAppFjxxb);
	}
	
	private void reset() {
		savePath = "";
		uuid = "";
		savePath1 = "";
		uuid1 = "";
		edit_fjmc.setText("");
		img_tp.setImageDrawable(this.getResources().getDrawable(R.drawable.icon_addpic_unfocused));
	}
	
	public void updateGridView(){
		adapter.notifyDataSetChanged();
	}

	@Override
	public void showProgressDialog(String msg) {
		// TODO Auto-generated method stub
		activity.showProgressDialog(msg);
	}

	@Override
	public void hideProgressDialog() {
		// TODO Auto-generated method stub
		activity.hideProgressDialog();
	}
	
	@Override
	public void showMessage(String msg){
		activity.showMessage(msg);
	}

	@Override
	public void saveSuccess(Long id) {
		// TODO Auto-generated method stub
		TAppFjxxb tAppFjxxb = new TAppFjxxb();
		tAppFjxxb = mTAppFjxxb;
		fjxxList.add(0,tAppFjxxb);
		updateGridView();
		reset();
	}

	@Override
	public void getAllFjxx(List<TAppFjxxb> arg0) {
		// TODO Auto-generated method stub
		
		for (TAppFjxxb mTAppFjxxb : arg0) {
			String wjlx=mTAppFjxxb.getWjmc();
			String wjlxx = wjlx.substring(wjlx.lastIndexOf(".") + 1, wjlx.length());
			mTAppFjxxb.setWjlx(wjlxx);
			mTAppFjxxb.setAppdz(ToolUtil.getFilePath(mTAppFjxxb.getUuid() +"."+wjlxx));
			if(mTAppFjxxb.getSczt() == 0 || mTAppFjxxb.getSczt() == 3) {
				String filePath =ToolUtil.getFilePath(mTAppFjxxb.getUuid() +"."+wjlxx);
				if(!filePath.startsWith(Environment.getExternalStorageDirectory().toString())){
					filePath = Environment.getExternalStorageDirectory() + filePath;
				}
		         File file = new File(filePath);
		         if(file.exists()) {
		        	 fjxxList.add(mTAppFjxxb);
		         }
			}else {
				fjxxList.add(mTAppFjxxb);	
			}
		}
		
		updateGridView();
	}

	@Override
	public void saveSuccess(int size) {
		// TODO Auto-generated method stub
		
	}


}
